import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { GradeClass } from 'src/entities/grade.entity';
import { CreateGradeDto } from './dto/create-grade.dto';
import type { PaginationResult, QueryParams } from 'src/types';

@Injectable()
export class GradesService {
  constructor(
    @InjectRepository(GradeClass)
    private gradesRepository: Repository<GradeClass>,
  ) {}

  create(createGradeDto: CreateGradeDto) {
    return this.gradesRepository.save(createGradeDto);
  }

  async list(queryParams: QueryParams): Promise<PaginationResult<GradeClass>> {
    const queryBuilder = this.gradesRepository.createQueryBuilder('grade');
    const { currentPage, pageSize } = queryParams;

    queryBuilder.take(pageSize).skip((currentPage - 1) * pageSize);
    const [recordsRaw, total] = await queryBuilder.getManyAndCount();

    const records = recordsRaw;

    return {
      currentPage: Number(currentPage),
      totalPages: Math.ceil(total / pageSize),
      total: Number(total),
      pageSize: Number(pageSize),
      list: records,
    };
  }
}
